package com.frontop.terminal.vlcjplayer.view;

import com.frontop.terminal.vlcjplayer.view.action.Resource;

import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

/**
 * @author Guodong
 */
public abstract class AbstractOnDemandMenu implements MenuListener {

    private final JMenu menu;

    private final boolean clearOnPrepare;

    public AbstractOnDemandMenu(Resource resource) {
        this(resource, false);
    }

    public AbstractOnDemandMenu(Resource resource, boolean clearOnPrepare) {
        this.menu = new JMenu(resource.name());
        this.menu.setMnemonic(resource.mnemonic());
        this.menu.addMenuListener(this);
        this.clearOnPrepare = clearOnPrepare;
        onCreateMenu(this.menu);
    }

    public final JMenu menu() {
        return menu;
    }

    @Override
    public final void menuSelected(MenuEvent e) {
        if (clearOnPrepare) {
            menu.removeAll();
        }
        onPrepareMenu(menu);
        menu.setEnabled(menu.getItemCount() > 0);
    }

    @Override
    public final void menuDeselected(MenuEvent e) {
    }

    @Override
    public final void menuCanceled(MenuEvent e) {
    }

    protected void onCreateMenu(JMenu menu) {
    }

    /**
     * 准备添加菜单
     *
     * @param menu 菜单对象
     */
    protected abstract void onPrepareMenu(JMenu menu);
}
